import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from functools import partial

from DataBean import ImageBean
import BcyImgDownloader
import BCYThread
import json

model = QStandardItemModel()
model.setHorizontalHeaderLabels(['相册','链接','名称','宽','高'])
all_img_bean = []

def show_url_list(ui, imgbean):
    global all_img_bean
    ui.te_detail.append(imgbean.getImgUrl())
    all_img_bean.append(imgbean)
    model.appendRow([
        QStandardItem(imgbean.getAlbum()),
        QStandardItem(imgbean.getImgUrl()),
        QStandardItem(imgbean.getImgName()),
        QStandardItem(str(imgbean.getImgWidth())),
        QStandardItem(str(imgbean.getImgHeight()))
        ])

def show_download_status(ui, msg):
    ui.te_detail.append(msg)
    ui.progressBar.setValue(ui.progressBar.value() + 1)
    if ui.progressBar.value() == ui.progressBar.maximum():
        ui.btn_download.setEnabled(True)


def click_success(ui):
    str = ui.le_url.text()
    print (str)
    if len(str) > 0:
        bcy_thread = BCYThread.UrlGetThread(str)
        ui.te_detail.setText(str)
        bcy_thread.url_signal.connect(partial(show_url_list, ui))
        bcy_thread.start()
        bcy_thread.exec()
    else:
        ui.te_detail.append("待解析的网络链接为空!")
        QMessageBox.warning(None, '警告', '待解析的网络链接为空!')

def get_filedir(ui):
    str = QFileDialog.getExistingDirectory(None, "请选择文件夹路径", "D:\\")
    ui.le_dlsrc.setText(str)

def save_json_file(ui):
    global all_img_bean
    if len(all_img_bean) > 0:
        print ("save json file...")
        sjf = QFileDialog.getSaveFileName(None,'选择保存Json文件的位置','./','Json文件(*.json)','Json文件(*.json)')
        print (sjf)
        with open(sjf[0], 'w') as s_json_obj:
            json_str = json.dumps(all_img_bean, default=lambda o: o.__dict__, sort_keys=True, ensure_ascii=False)
            # print (json_str)
            json.dump(json_str, s_json_obj)
    else:
        ui.te_detail.append("待存储的列表为空!")
        QMessageBox.warning(None, '警告', '待存储的列表为空!')

def load_json_file(ui):
    print ("load json file...")
    ljf = QFileDialog.getOpenFileName(None,'选择一个Json文件','./','Json文件(*.json)','Json文件(*.json)')
    print (ljf)
    with open(ljf[0]) as l_json_obj:
        jstr = json.load(l_json_obj)
        jstr = '{' + '"data":' + jstr + '}'
        img_beans = json.loads(jstr)
        print (type(img_beans))
        print (img_beans.keys())
        if len(img_beans) > 0:
            for img in img_beans['data']:
                img_bean = ImageBean()
                img_bean.setAlbum(img['album'])
                img_bean.setImgUrl(img['imgurl'])
                img_bean.setImgName(img['imgname'])
                img_bean.setImgWidth(img['imgwidth'])
                img_bean.setImgHeight(img['imgheight'])
                show_url_list(ui, img_bean)
        else:
            ui.te_detail.append("加载的列表文件为空!")
            QMessageBox.warning(None, '警告', '加载的列表文件为空!')

def clear_url_list(ui):
    global all_img_bean
    #清空数据列表
    all_img_bean.clear()
    #清空model的数据对象
    model.removeRows(0, model.rowCount())

def start_download(ui):
    global all_img_bean
    save_path = ui.le_dlsrc.text()
    if len(all_img_bean) > 0 and len(save_path) > 0:
        ui.progressBar.setMaximum(len(all_img_bean))
        ui.progressBar.setValue(0)
        ui.btn_download.setEnabled(False)
        download_thread = BCYThread.ImgDownloadThread(all_img_bean, save_path)
        download_thread.download_signal.connect(partial(show_download_status, ui))
        download_thread.start()
        download_thread.exec()
    else:
        ui.te_detail.append("下载列表为空！")
        QMessageBox.warning(None, '警告', '下载列表为空！')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    MainWindow = QMainWindow()
    ui = BcyImgDownloader.Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    ui.tv_urldata.setModel(model)
    # ui.tv_urldata.horizontalHeader().setStretchLastSection(True)
    # ui.tv_urldata.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
    # ui.tv_urldata.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
    ui.tv_urldata.verticalHeader().setVisible(False)
    ui.tv_urldata.horizontalHeader().setStyleSheet("QHeaderView::section{background:lightgray;}")
    ui.tv_urldata.verticalHeader().setStyleSheet("QHeaderView::section{background:lightgray;}")
    ui.tv_urldata.horizontalHeader().setSectionsClickable(False)
    ui.tv_urldata.verticalHeader().setSectionsClickable(False)
    ui.tv_urldata.setEditTriggers(QAbstractItemView.NoEditTriggers)
    ui.tv_urldata.setSelectionBehavior(QAbstractItemView.SelectRows)
    ui.tv_urldata.setColumnWidth(0, 149)
    ui.tv_urldata.setColumnWidth(1, 540)
    ui.tv_urldata.setColumnWidth(2, 230)
    ui.tv_urldata.setColumnWidth(3, 65)
    ui.tv_urldata.setColumnWidth(4, 65)
    ui.btn_urlanalyze.clicked.connect(partial(click_success, ui))
    ui.btn_dirselect.clicked.connect(partial(get_filedir, ui))
    ui.btn_download.clicked.connect(partial(start_download, ui))
    ui.btn_savelist.clicked.connect(partial(save_json_file, ui))
    ui.btn_loadlist.clicked.connect(partial(load_json_file, ui))
    ui.btn_clearlist.clicked.connect(partial(clear_url_list, ui))
    sys.exit(app.exec_())